package org.example.api;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

//实现对账号服务的远程调用
@Service
public class AccountService {

    private static Logger logger = LoggerFactory.getLogger(AccountService.class) ;

    //1.ribbon 的方式
    @Autowired
    private RestTemplate restTemplate ;

    @Autowired
    private AccountServiceFeign accountServiceFeign ;

    //2.feign 的方式
    public void debit(String userId, int orderMoney) {
//        ResponseEntity<Void> entity = restTemplate.getForEntity( "http://account-service/debit/{userId}/{orderMoney}", Void.class, userId, orderMoney );
//        if(entity.getStatusCode()== HttpStatus.OK){
//            logger.info("扣减用户{}金额成功，本次扣减的数目为{}",userId,orderMoney);
//            return ;
//        }
//        logger.info("扣减用户{}金额失败",userId);
//        throw new RuntimeException("扣减金额失败") ;

        ResponseEntity<Void> entity = accountServiceFeign.debit(userId, orderMoney);
        if(entity.getStatusCode()== HttpStatus.OK){
            logger.info("扣减用户{}金额成功，本次扣减的数目为{}",userId,orderMoney);
            return ;
        }
        logger.info("扣减用户{}金额失败",userId);
        throw new RuntimeException("扣减金额失败") ;
    }
}
